  <template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="5" :offset="0">
            <el-form-item label="资料名称">
              <el-input v-model="searchForm.title" placeholder="资料名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
  
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        

        <el-table-column label="资料名称" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.title }}
          </template>
        </el-table-column>
  
        <el-table-column label="资料描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.description }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="文件类型" align="center">
          <template #default="{ row }">
            {{ transferFileType(row.fileType) }}
          </template>
        </el-table-column> -->
  
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            {{ row.state==0?"下架":"上架" }}
          </template>
        </el-table-column>
  
        <el-table-column label="创建人" align="center">
          <template #default="{ row }">
            {{ row.createUsername }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="400" align="center">
          <template #default="scope">
              <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
              <div v-else>
    
                <el-button type="primary" size="small" text @click="openFileView(scope.row)">查看文件</el-button>

                <el-button v-if="scope.row.state=='0'" type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
                <el-button v-else type="primary" size="small" text disabled @click="handleEdit(scope.row)">修改</el-button>


                <el-popconfirm v-if="scope.row.state=='0'" title="是否要上架该资料？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="chageInfoLibState(scope.row.id,1)">
                    <template #reference>
                        <el-button type="primary" size="small" text>上架</el-button>
                    </template>
                </el-popconfirm>

                <el-popconfirm  v-if="scope.row.state=='1'" title="是否要下架该资料？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="chageInfoLibState(scope.row.id,0)">
                    <template #reference>
                        <el-button type="primary" size="small" text>下架</el-button>
                    </template>
                </el-popconfirm>
            
                <el-popconfirm title="是否要删除该手册？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="handleDelete(scope.row.id)">
                    <template #reference>
                    <el-button v-if="scope.row.state=='0'" text type="primary" size="small">删除</el-button>
                    <el-button v-else text type="primary" size="small" disabled>删除</el-button>
                    </template>
                </el-popconfirm>
              </div>
          </template>
        </el-table-column>

      </el-table>
  
      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="initTableData" />
      </div>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
          
          <el-form-item label="资料名称" prop="title">
            <el-input v-model="form.title" placeholder="资料名称"></el-input>
          </el-form-item>
  
          <el-form-item label="资料描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="form.description" placeholder="资料描述"></el-input>
          </el-form-item>

          <el-form-item label="资料文件" prop="fileList" v-if="editId == 0">
            <el-upload
                class="upload-demo"
                ref="upload"
                accept=".docx,.zip,.pdf,.jpg,.png,.xlsx,.xls"
                action=""
                :limit="1"
                :on-change="fileChange"
                :file-list="form.fileList"
                :before-upload="beforeUpload"
                :on-exceed="handleExceed"
                :http-request="uploadSubmit"
                :auto-upload="false">
                <el-button size="small" type="primary">选取文件</el-button>
                <div class="el-upload__tip" style="display: inline-block;margin-left: 20px">请选择PDF、Word、Excel、图片或者ZIP包文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </FormDrawer>
  
    </el-card>

    <!-- 查看文件 -->
    <el-dialog v-model="showFileViewVisible" title="查看文件" width="800" align-center>

        <div style="padding-top: 5px;"  v-for="(item, index) in filesInfo" :key="index">
          <span>{{ item.name }}</span>
          &nbsp;&nbsp;&nbsp
          <el-button type="primary" text @click="browseFile(item)">浏览</el-button>
          <el-button type="primary" text @click="downloadFile(item.url)">下载文件</el-button>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="showFileViewVisible = !showFileViewVisible">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 浏览word文件 -->
    <DocxViewer ref="docxViewerRef"></DocxViewer>

    <!-- 浏览pdf文件 -->
    <PDFViewer ref="pdfViewerRef"></PDFViewer>

  </template>

  <script setup>
  import { ref, reactive, computed, onMounted } from "vue"
  import FormDrawer from "~/components/FormDrawer.vue";
  import {toast,toastWarn} from "~/composables/util"
  import { dateFormatter } from '~/utils/common.js'
  import { addInfoLibrary, getInfoLibraryList,editInfoLibrary,deleteInfoLibrary,updateInfoLibState,downloadInfoLibFile } from "~/api/supply"
  import DocxViewer from '~/components/docxView.vue';
  import PDFViewer from '~/components/pdfView.vue';


  // 分页
  const currentPage = ref(1)
  const total = ref(0)
  const limit = ref(10)
  
  //上传组件
  const upload = ref(null)

  // 查询条件
  const searchForm = reactive({
    title: "",
    //资料类型（0：操作手册 1：常见问答）
    type: "0",
    page: currentPage.value,
    size: limit.value,
  })
  // 重置搜索框
  const resetSearchForm = () => {
    searchForm.title = ""
    initTableData(1)
  }
  
  const tableData = ref([])
  const loading = ref(false)
  

  // 查看文件信息弹窗
  const showFileViewVisible = ref(false)
  const filesInfo = ref([])
  const docxViewerRef = ref(null)
  const pdfViewerRef = ref(null)
  
  
  // 生命周期函数
  onMounted(() => {
    //初始化列表数据
    initTableData()
  })
  
  
  // 获取数据
  function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
      currentPage.value = p
    }
  
    loading.value = true
    searchForm.page = currentPage.value

    getInfoLibraryList(searchForm)
      .then(res => {
          if(res){
            tableData.value = res.records      
            total.value = res.total
          }else{
            tableData.value = []  
            total.value = 0
          }
      })
      .finally(() => {
        loading.value = false
      })
  }
  
  // 删除
  const handleDelete = (id) => {
    loading.value = true
    deleteInfoLibrary(id).then(res => {
        toast("删除成功")
        initTableData()
    })
    .finally(() => {
        loading.value = false
    })
  }
  
  // 表单部分
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const form = reactive({
    title: "",
    description: "",
    fileList: []
  })
  //执行表单校验
  const rules = {
    title: [
      { required: true, message: '资料名称不能为空', trigger: 'change' }
    ],
    description: [
      { required: true, message: '资料描述不能为空', trigger: 'change' }
    ],
    fileList: [
      { required: true, message: '请选择文件', trigger: 'change' }
    ]
  }
  
  //是否是编辑弹窗
  const editId = ref(0)
  const drawerTitle = computed(() => editId.value ? "修改" : "新增")
  
  //提交表单
  const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
      if (!valid) return

        //新增
        if(editId.value == 0){
             //触发文件上传
            upload.value.submit();
        }else{
            //loading
            formDrawerRef.value.showLoading()
            //修改
            const fun = editInfoLibrary(editId.value,form)
            fun.then(res => {
                toast(drawerTitle.value + "成功")
                initTableData(editId.value ? false : 1)
                formDrawerRef.value.close()
            })
            .finally(() => {
                formDrawerRef.value.hideLoading()
            })
        }
    })
  }
  
  // 重置表单
  function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
      for (const key in form) {
        form[key] = row[key]
      }
    }
  }
  
  // 新增按钮点击事件
  const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        title: "",
        description: "",
        filelist: []
    })
    //打开弹窗
    formDrawerRef.value.open()
  }
  
  // 编辑
  const handleEdit = (row) => {
    editId.value = row.id
    resetForm(row)
    formDrawerRef.value.open()
  }

  // 打开文件弹窗
  const openFileView = (row) => {
    downloadInfoLibFile(row.id).then(res => {
      if(res){
        filesInfo.value = res
        showFileViewVisible.value = true
      }else{
        toastWarn("获取文件信息失败")
      }
    })
  }

  // 浏览
  const browseFile = (file) => {
    if(file.type == '2'){
      //word
      docxViewerRef.value.showDocVisible(file.url)
    }else if(file.type == '1'){
      //pdf
      pdfViewerRef.value.showDocVisible(file.url)
    }
  }

  // 下载
  const downloadFile = (url) => {
    window.location.href = url
  }

  // 上传组件 -------------------------------------------
  // 文件改变
  const fileChange = (file, fileList) => {
      //console.log("fileChange =================" + JSON.stringify(file))
      //console.log("fileList =================" + JSON.stringify(fileList))
      form.fileList = fileList;
  }

  // 文件超出个数限制
  const handleExceed = (file, fileList) => {
      toastWarn('只能选择一个文件');
  }

  // 上传前 文件校验
  const beforeUpload = (file) => {
      //console.log("==============" + JSON.stringify(file))
      const isLt2M = file.size / 1024 / 1024 < 30
      if (!isLt2M) {
          toastWarn('上传文件大小不能超过 30MB!')
          return false;
      }
      return true;
  }

  //提交上的文件
  const uploadSubmit = (param) => {

      let fileObj = param.file// 相当于input里取得的files
      let paramIo = new FormData()// FormData 对象
      paramIo.append('files', fileObj)// 文件对象
      paramIo.append('title', form.title)
      paramIo.append('description', form.description)
      //资料类型（0：操作手册 1：常见问答）
      paramIo.append('type', '0')

      //添加资料库
      //loading
      formDrawerRef.value.showLoading()
      const fun = addInfoLibrary(paramIo)
      fun.then(res => {
          toast(drawerTitle.value + "成功")
          //清空file文件
          upload.value.clearFiles(); 
          //修改刷新当前页，新增刷新第一页
          initTableData(editId.value ? false : 1)
          formDrawerRef.value.close()
      })
      .finally(() => {
          //close loading
          formDrawerRef.value.hideLoading()
      })
  }
  // 上传组件 -------------------------------------------


  // 上架|下架资料
  const chageInfoLibState = (id,status) => {
    updateInfoLibState(id,status).then(res => {
        if(status=="1"){
            toast("上架成功")
        }else{
            toast("下架成功")
        }
        initTableData()
    })
    .finally(() => {
    })
  }
  </script>